package ua.kpi.apolonov.questions;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import ua.kpi.apolonov.answers.Answer;

/**
 * Structure of question
 * @version 4.3 18.03.2013
 * @author Yegor Apolonov 
 */

public class Question implements Iterable<Answer>, Cloneable, Serializable {
    private String question;
    private String inquiry;
    private List<Answer> answer = new ArrayList<Answer>();
    
    public Question(String question, List<Answer> answers) {
    	setInquiry("\nВведите ответ в нужном формате\n>>");
    	this.question = question;
        for (Answer answer : answers) {
        	this.answer.add(answer.clone());
        }
    }
    
    public String getQuestionText() {
        return question;
    }
    
    public Answer getAnswer(int index) {
    	return answer.get(index).clone();
    }
    
    public String getInquiry() {
    	return inquiry;
    }
    
    public float inspectAnswers(String userAnswers) {
        return 0;
    }
    
    public Iterator<Answer> iterator() {
    	return answer.iterator();
    }
    
    @Override
    public Question clone() throws CloneNotSupportedException {
    	Question clonedQuestion = (Question) super.clone();
    	Question question = null;
    	try {
    		question = getDeepCloning(clonedQuestion);
    	} catch (IOException | ClassNotFoundException e) {
    		e.printStackTrace();
    	}
    	return question;
    }
    
    protected void setInquiry(String inquiry) {
    	this.inquiry = inquiry;
    }

    private Question getDeepCloning(Question question) throws IOException, ClassNotFoundException {
    	ByteArrayOutputStream baos = new ByteArrayOutputStream();
    	ObjectOutputStream oos = new ObjectOutputStream(baos);
    	oos.writeObject(question);
    	ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    	ObjectInputStream ois = new ObjectInputStream(bais);
    	Question clonedQuestion = (Question)ois.readObject();
    	oos.flush();
    	oos.close();
    	baos.flush();
    	baos.close();
    	ois.close();
    	bais.close();
    	return clonedQuestion;
    }
}
